package ConcurrentHashMap_10;
import java.util.concurrent.ConcurrentHashMap;
public class 原子操作_computeIfAbsent {
    public static void main(String[] args) {
        final ConcurrentHashMap<String, Integer> wordCountMap = new ConcurrentHashMap<>();
        final String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};
        final int THREAD_COUNT = 10;

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String word = words[threadId % words.length];
                        Thread.sleep((long)(Math.random() * 50)); // 模拟处理时间

                        // 原子性地更新词频
                        wordCountMap.compute(word, (key, value)->{
                            return value == null ? 1 : value + 1;
                        });

                        System.out.println(Thread.currentThread().getName() +
                                                   " 处理单词: " + word + " 当前计数: " + wordCountMap.get(word));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "处理线程-" + i).start();
        }

        // 等待所有线程完成
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终词频统计: " + wordCountMap);
    }
}